package com.trm.index.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.trm.role.dao.RoleDao;

public class IndexServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }

    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // String page = request.getParameter("page");
        HttpSession session = request.getSession();
        Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
        Map<String, Object> role = (Map<String, Object>) session.getAttribute("role");
        request.setAttribute("user", user);
        String right = role.get("right").toString();
        request.setAttribute("right", right);
        RoleDao roleDao = new RoleDao();
        // 获得当前权限可查看角色
        List<Map<String, Object>> list = roleDao.getRightRoleList(right);
        request.setAttribute("list", list);
        // 指定默认主页
        String homepage = (String) user.get("homepage");
        String mainSrc = "";
        String curMenu = "";
        if (homepage != null && !"".equals(homepage) && !"userInfo".equals(homepage) && !"userInfo".equals(homepage)) {
            mainSrc = "StudentServlet?role=" + homepage;
            for (Map<String, Object> roleMap : list) {
                if (homepage.equals(roleMap.get("id").toString())) {
                    curMenu = roleMap.get("role").toString() + "信息";
                }
            }
        } else if ("manager".equals(homepage)) {
            mainSrc = "manager/manager.jsp";
            curMenu = "系统管理";
        } else {
            mainSrc = "StudentServlet?action=edit&role=" + role.get("id") + "&id=" + user.get("id") + "&type=self";
            curMenu = "个人信息";
        }
        if (curMenu == null || "".equals(curMenu)) {
            mainSrc = "StudentServlet?action=edit&role=" + role.get("id") + "&id=" + user.get("id") + "&type=self";
            curMenu = "个人信息";
        }
        request.setAttribute("curMenu", curMenu);
        request.setAttribute("mainSrc", mainSrc);
        // 主页url
        String indexUrl = "/index.jsp";
        // 判断移动端页面
        String type = session.getAttribute("loginType").toString();
        if ("mobile".equals(type)) {
            indexUrl = "/mobile/index.jsp";
        }
        try {
            request.getRequestDispatcher(indexUrl).forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }
}
